<template>
  <div class="courseManagement">
    <div class="operate-container">
      <div class="leftArea">
        <b style="margin-right: 14px;">商家名称：{{ merchantName }}</b>
        <el-input
          style="width: 210px"
          v-model="searchParams.name"
          placeholder="请输入商品名称"
        />
        <span>商品状态</span>
        <el-select
          style="width: 160px"
          clearable
          v-model="searchParams.state">
          <el-option
            v-for="item in stateOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button
          class="marginLeft14"
          type="primary"
          @click="handleSearch">
          查询
        </el-button>
      </div>
      <div class="rightArea">
        <el-button
          type="primary"
          @click="handleCreateShop">
          新增商品
        </el-button>
      </div>
    </div>
    <div class="inner-container">
      <el-table
        stripe
        v-loading="loading"
        :data="tableData"
        :height="'calc(100vh - 245px)'">
        <el-table-column
          fixed
          align="left"
          label="序号"
          width="60">
          <template #default="scope">
            {{ (searchParams.pageNum - 1) * searchParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="商品图片">
          <template #default="scope">
            <el-image
              v-if="scope.row.picFile && scope.row.picFile.hasOwnProperty('url')"
              :preview-src-list="[scope.row.picFile.url]"
              :src="scope.row.picFile.url"
              :preview-teleported="true"
              style="width: 48px; height: 48px"
              z-index="100"
              fit="contain">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column align="left" label="商品名称" prop="name"></el-table-column>
        <el-table-column align="left" label="商品价格" prop="price"></el-table-column>
        <el-table-column align="left" label="商品状态" prop="state">
          <template #default="scope">
            <span v-if="scope.row.state === 1">上架</span>
            <span v-if="scope.row.state === 0">下架</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="添加日期" prop="createTime"></el-table-column>
        <el-table-column align="left" label="备注" prop="remark"></el-table-column>
        <el-table-column align="left" label="操作" width="160">
          <template #default="scope">
            <el-button size="small" @click="handleEditShop(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDeleteShop(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[20, 50, 100]"
          :total="searchParams.total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="searchParams.pageNum"
          :page-size="searchParams.pageSize"
        />
      </div>
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500"
        :before-close="handleCloseDialog">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="auto">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input v-model="ruleForm.price" />
          </el-form-item>
          <el-form-item label="商品状态" prop="state">
            <el-select
              style="width: 100px"
              v-model="ruleForm.state">
              <el-option
                v-for="item in stateOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              :autosize="{ minRows: 2, maxRows: 6 }"
              resize="none"
              maxlength="300"
              show-word-limit
              type="textarea"
              v-model="ruleForm.remark"
            />
          </el-form-item>
          <el-form-item label="标签" prop="tags">
          <el-input-tag
            v-model="ruleForm.tags"
            placeholder="请输入回车"
            draggable
          />
          </el-form-item>
          <el-form-item label="商品图片" prop="picFile">
            <el-upload
              class="avatar-uploader"
              :accept="accept"
              ref="upload2"
              :action="uploadUrl"
              :headers="headers"
              :show-file-list="false"
              :on-success="(res) => handlePicSuccess(res, 'picFile')">
              <img
                v-if="ruleForm.picFile && ruleForm.picFile.hasOwnProperty('url')"
                :src="ruleForm.picFile.url"
                class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCloseDialog">取消</el-button>
            <el-button type="primary" @click="handleSubmitDialog">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { getToken } from "@/utils/auth";
import { ElMessage } from 'element-plus';
import { listGoods, getGoods, addGoods, updateGoods, delGoods } from "@/api/course/index.js";
import {handleConfirmDelete} from "@/utils/myUtils.js";

const stateOption = reactive([
  { label: '上架', value: 1},
  { label: '下架', value: 0 }
])

const route = useRoute();
const merchantId = route.query.id;
const name = route.query.name;
const merchantName = ref(name);
const searchParams = reactive({
  name: "",
  state: undefined,
  merchantId,
  pageNum: 1,
  pageSize: 20,
  total: 0,
})

//列表数据获取
onMounted(() => { getTableData() })
const tableData = ref([]);
const loading = ref(false)
const getTableData = () => {
  loading.value = true
  const params = { ...searchParams };
  listGoods(params).then(response => {
    tableData.value = response.rows;
    searchParams.total = response.total;
    loading.value = false;
  })
}

const handleSearch = () => {
  searchParams.pageNum = 1;
  getTableData();
}

const handleCurrentChange = (v) => {
  searchParams.pageNum = v;
  getTableData();
}

const handleSizeChange = (v) => {
  searchParams.pageNum = 1;
  searchParams.pageSize = v;
  getTableData();
}

//删除商品
const handleDeleteShop = async (data) => {
  await handleConfirmDelete()
  const { id } = data
  delGoods(id).then(response => {
    getTableData();
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
  })
}

//新增与编辑
const dialogVisible = ref(false)
const dialogTitle = ref("");
const ruleFormRef = ref(null);
const ruleForm = reactive({
  id: undefined,
  merchantId,
  name: '',
  price: "",
  state: 1,
  remark: "",
  tags: [],
  picFile: null,
})
const rules = reactive({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
  ],
  picFile: [
    { required: true, message: '请上传商品图片', trigger: 'blur' },
  ],
})

const handleCloseDialog = () => {
  dialogVisible.value = false;
  ruleFormRef.value.resetFields()
}
const handleSubmitDialog = async() => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      const { tags } = ruleForm;
      const params = {
        ...ruleForm,
        tags: tags.length ? tags.join(",") : '',
      };
      if (dialogTitle.value === "新增商品") {
        addGoods(params).then(response => {
          ElMessage.success('新增成功')
          getTableData();
          handleCloseDialog();
        })
      } else if (dialogTitle.value === "编辑商品") {
        updateGoods(params).then(response => {
          ElMessage.success('编辑成功')
          getTableData();
          handleCloseDialog();
        })
      }
    }
  })
}

// 上传的图片服务器地址
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload")
const headers = ref({ Authorization: "Bearer " + getToken() });
const accept = ref("image/png, image/jpeg, image/jpg");
const handlePicSuccess = (response, fieldName) => {
  const { id, fileName, oldName, url } = response;
  ruleForm[fieldName] = { id, name: fileName, url, route: oldName }
}

//新增分类
const handleCreateShop = () => {
  ruleForm.id = undefined;
  ruleForm.name = '';
  ruleForm.price = '';
  ruleForm.state = 1;
  ruleForm.remark = '';
  ruleForm.tags = [];
  ruleForm.picFile = null;
  dialogTitle.value = "新增商品";
  dialogVisible.value = true;
}

//编辑分类
const handleEditShop = (data) => {
  const { id } = data;
  getGoods(id).then(response => {
    const { data } = response;
    const { id, name, price, state, remark, tags, picFile  } = data;
    ruleForm.id = id;
    ruleForm.name = name;
    ruleForm.price = price;
    ruleForm.state = state;
    ruleForm.remark = remark;
    ruleForm.tags = tags.split(',');
    ruleForm.picFile = picFile;
    dialogTitle.value = "编辑商品";
    dialogVisible.value = true;
  })
}
</script>
<style lang="scss" scoped>
.courseManagement {
  width: 100%;
  padding: 15px;
  >div.operate-container {
    width: 100%;
    height: 60px;
    padding: 0 15px;
    box-sizing: border-box;
    margin-bottom: 15px;
    background-color: #f5f6f8;
    display: flex;
    align-items: center;
    justify-content: space-between;
    >div.leftArea {
      display: flex;
      align-items: center;
      span {
        color: #343d59;
        font-size: 14px;
        &:not(:first-child) {
          margin: 0 14px;
        }
      }
      .el-select {
        width: 200px;
        :deep( .el-input__inner ){
          height: 30px !important;
        }
      }
    }
    >div.rightArea {

    }
  }
  >div.inner-container {
    div.pagination {
      height: 40px;
      line-height: 40px;
      background-color: #ffffff;
      margin-top: 10px;
      .el-pagination {
        float: right;
        margin-right: 30px;
      }
    }
  }
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  text-align: center;
}
</style>
